<template>
  <div class="container">
    <navigate> 编辑家庭情况 </navigate>
    <div class="title flex_row flex_align_center">
      <div class="bar"></div>
      <div class="text">家庭背景概况</div>
    </div>

    <div class="card_family_bg">
      <template v-for="(item, i) in list">
        <van-cell-group
          v-if="item.opition_type == 1"
          class="input_outer father_relative"
        >
          <van-field
            readonly
            clickable
            v-model="item.val.name"
            :label="item.name"
            placeholder="请选择"
            @click="item.visible = true"
          />
          <v-picker
            :columns="item.templateOptions"
            valueKey="name"
            @confirm="
              item.val = $event;
              item.visible = false;
            "
            :isVisible="item.visible"
            @cancel="item.visible = false"
          />
          <img
            src="@/assets/images/common/right.png"
            class="right vertical_center"
            alt=""
          />
        </van-cell-group>

        <van-cell-group
          :key="i + '-++'"
          class="input_outer"
          v-else-if="item.opition_type == 2"
        >
          <van-field
            v-model="item.val"
            :label="item.name"
            placeholder="请输入"
          />
        </van-cell-group>
      </template>
    </div>

    <div class="title flex_row flex_align_center">
      <div class="bar"></div>
      <div class="text">家庭关系问卷</div>
    </div>

    <div class="card_questionnaire">
      <div class="item" v-for="(item, index) in list3" :key="index">
        <div class="question">{{ index + 1 + "." + item.name }}</div>
        <textarea
          placeholder="请输入实际情况"
          v-model="item.val"
          v-if="item.opition_type == 2"
        ></textarea>
        <template v-else>
          <v-radio
            class="type2"
            v-for="(e, i) in item.templateOptions"
            :key="i"
            @selected="item.val.id = $event"
            :val="e.id"
            v-model="item.val.id"
            :idText="'text' + i + index + '_'"
            :name="`name${index}_`"
            :text="e.name"
          >
          </v-radio>
        </template>
      </div>
    </div>

    <div class="title flex_row flex_align_center">
      <div class="bar"></div>
      <div class="text">日常家庭生活情况</div>
    </div>
    <div class="card_questionnaire">
      <div class="item" v-for="(item, index) in list4" :key="index">
        <div :class="['question', { type2: item.opition_type == 2 }]">
          {{ item.name }}
        </div>
        <textarea
          placeholder="请输入实际情况"
          v-model="item.val"
          v-if="item.opition_type == 2"
        ></textarea>
        <template v-else>
          <v-radio
            class="type2"
            v-for="(e, i) in item.templateOptions"
            :key="i"
            @selected="item.val.id = $event"
            :val="e.id"
            v-model="item.val.id"
            :idText="'text' + i + index + '__'"
            :name="`name${index}__`"
            :text="e.name"
          >
          </v-radio>
        </template>
      </div>
    </div>

    <button class="btn" @click="save">保存资料</button>
  </div>
</template>

<script>
import {
  getTemplateList,
  submitSelfAssessment,
  queryArchivesResults,
} from "@/api/funcation/selfAssessment";
import { mapState } from "vuex";

export default {
  data() {
    return {
      list: [],
      list3: [],
      list4: [],
      familyMemberList: [{ list: [] }], // 家庭成员（当前未使用）
      quesition: [],
      list2: [],
      resultData: [],
      userArchivesResults: [], // 新增：存储接口返回的历史数据
    };
  },
  computed: {
    ...mapState(["INFO"]),
  },
  methods: {
    async getArchivesResults() {
      const par = {
        user_id: this.INFO.id,
        type_id: 2, // 与save方法的type_id保持一致
      };
      const res = await queryArchivesResults(par);
      if (res.code === 200 && res.data[0]?.content) {
        try {
          this.userArchivesResults = JSON.parse(res.data[0].content);
          console.log("接口返回的历史数据:", this.userArchivesResults);

          const allItems = [...this.list, ...this.list3, ...this.list4];
          this.userArchivesResults.forEach(({ questionId, answersId }) => {
            const targetItem = allItems.find(
              (item) => Number(item.id) === Number(questionId)
            );
            if (!targetItem) return;

            if (targetItem.opition_type === 1) {
              // 处理单选/下拉选项
              const option = targetItem.templateOptions.find(
                (opt) => opt.id === answersId
              );
              if (option) {
                if (this.list.includes(targetItem)) {
                  // list中的下拉项：赋值完整对象
                  this.$set(targetItem, "val", option);
                } else {
                  // list3/list4中的单选框：只更新id
                  this.$set(targetItem.val, "id", option.id);
                }
              }
            } else if (targetItem.opition_type === 2) {
              // 处理输入框/文本域
              this.$set(targetItem, "val", answersId);
            }
          });
        } catch (e) {
          console.error("数据回显失败:", e);
        }
      }
    },
    async getTemplateList(callback) {
      const res = await getTemplateList({ id: "2" });
      if (res.code === 200) {
        this.list = res.data[0].templates[0].children || [];
        this.list3 = res.data[0].templates[2].children || [];
        this.list4 = res.data[0].templates[3].children || [];

        // 初始化list（下拉/输入框）
        this.list.forEach((item) => {
          this.$set(item, "visible", false);
          this.$set(item, "val", item.opition_type === 1 ? {} : "");
        });

        // 初始化list3/list4（单选框/文本域）
        [this.list3, this.list4].forEach((list) => {
          list.forEach((item) => {
            this.$set(item, "visible", false);
            this.$set(item, "val", item.opition_type === 1 ? { id: "" } : "");
          });
        });

        callback && callback();
      }
    },
    async save() {
      // 构建提交数据
      const idPairs = [
        ...this.list.map((item) => ({
          questionId: item.id,
          answersId: item.opition_type === 1 ? item.val?.id : item.val,
        })),
        ...this.list3.map((item) => ({
          questionId: item.id,
          answersId: item.opition_type === 1 ? item.val?.id : item.val,
        })),
        ...this.list4.map((item) => ({
          questionId: item.id,
          answersId: item.opition_type === 1 ? item.val?.id : item.val,
        })),
      ];

      const params = {
        user_id: this.INFO.id,
        content: JSON.stringify(idPairs),
        type_id: 2, // 与getArchivesResults的type_id保持一致
        source: 1,
      };

      const res = await submitSelfAssessment(params);
      if (res.code === 200) {
        this.$toast.success("保存成功！");
      }
    },
    del(index) {
      if (this.familyMemberList.length === 1) {
        return this.$toast.fail("已经剩最后一条了！");
      }
      this.familyMemberList.splice(index, 1);
    },
    add() {
      const temp = this.familyMemberList[0].list.map((item) => {
        const copy = JSON.parse(JSON.stringify(item));
        copy.val = "";
        return copy;
      });
      this.familyMemberList.push({ list: temp });
    },
  },
  async created() {
    await this.getTemplateList();
    await this.getArchivesResults(); // 确保模板加载后再回显数据
  },
};
</script>

<style lang="less" scoped>
@import "./css/index.less";
@import "../styles/common.less";
</style>
